// pages/detail/detail.js
import { getOne, get, inc, incLike, add } from '../../utils/db'
Page({
  data: {
    list: [],
    detail: {},
    imgs: [],
    id: '',
    isLike: false
  },
  // 渲染页面
  async onLoad(e) {
    this.data.id = e.id;
    this.getDetail();
    // 判断是否关注
    var openid = wx.getStorageSync("openid");
    var menuId = this.data.id;
    var result = await get("likes", { _openid: openid, menuId: menuId });
    console.log(result.data);
    if (result.data.length > 0) {		//已关注
      this.setData({
        isLike: true
      })
    } else {//未关注
      this.setData({
        isLike: false
      })
    }
  },

  // 添加关注
  async addLike() {
    var result = await add('likes', { menuId: this.data.id }).catch(err => console.log(err)) //添加到likes记录
    var result = await incLike('menu', this.data.id) //更新menu数量,likes累加1
    this.data.detail.like += 1; //页面更新
    this.setData({
      isLike: true,
      detail: this.data.detail
    })
  },
  // 取消关注
  cancelLike() {
    var openid = wx.getStorageSync('openid') // 通过云函数修改
    // console.log(openid);
    wx.cloud.callFunction({
      name: 'cancelLike',
      data: {
        openid: openid,
        menuId: this.data.id
      }
    })
      .then(async res => {
        var result = await incLike('menu', this.data.id, -1)//menu中like减1
        this.data.detail.like -= 1;// 页面like减少1
        this.setData({
          detail: this.data.detail,
          isLike: false
        })
      })
      .catch(err => {
        console.log(err)
      })

  },
  // 获取数据详情
  async getDetail() {
    var result = await inc('menu', this.data.id, 1).catch(err => console.log(err))// 增加访问量,
    var result = await getOne('menu', this.data.id)//数据详情
    // console.log(result);
    this.setData({
      list: result.data,
      imgs: result.data.image
    })
  },
  // 查大图
  previewImage(e) {
    var url = e.currentTarget.dataset.url
    wx.previewImage({
      urls: this.data.imgs,
      current: url
    })
  }
})